﻿using AutoMapper;
using MediatR;
using SmartTracking.API.Read.Application.Commands.Descendant_Files;
using SmartTracking.API.Read.DTO;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.Descendant_Files
{
    /// <summary>
    /// 后裔档案下拉框菜单命令处理器
    /// </summary>
    public class GetDescendantFileMenuCommandHandler : IRequestHandler<GetDescendantFileMenuCommand, ApiResult<List<ResMenuitemOutput>>>
    {
        private readonly IBaseRepository<DescendantFile> _descendantRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetDescendantFileMenuCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="descendantRepository">后裔档案仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetDescendantFileMenuCommandHandler(
            IBaseRepository<DescendantFile> descendantRepository,
            IMapper mapper,
            ILogger<GetDescendantFileMenuCommandHandler> logger)
        {
            _descendantRepository = descendantRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理后裔档案下拉框菜单查询命令
        /// </summary>
        /// <param name="request">后裔档案下拉框菜单查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>下拉框菜单项列表</returns>
        public Task<ApiResult<List<ResMenuitemOutput>>> Handle(GetDescendantFileMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询所有未被删除的后裔档案，并转换为下拉框菜单项格式
                var entities = _descendantRepository.GetAll()
                    .Where(df => !df.IsDeleted&&!df.Initialstate)
                    .Select(df => new ResMenuitemOutput
                    {
                        value = df.DescendantId,
                        label = df.EarSignal
                    })
                    .ToList();

                _logger.LogInformation($"后裔档案下拉框菜单查询成功，共获取 {entities.Count} 条记录");
                return Task.FromResult(new ApiResult<List<ResMenuitemOutput>>
                {
                    Code = ApiEnum.查询成功,
                    Message = "查询成功",
                    data = entities
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"后裔档案下拉框菜单查询时发生系统异常: {ex.Message}");
                return Task.FromResult(new ApiResult<List<ResMenuitemOutput>>
                {
                    Code = ApiEnum.查询失败,
                    Message = "系统异常，请联系管理员",
                    data = null
                });
            }
        }
    }
}
